"use client"
import React, { useState } from 'react';
import Script from 'next/script';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { useRouter } from 'next/navigation';
import { ProcessingDialog } from "@/components/processing-dialog"
import Web3 from 'web3';
import axios from 'axios';

let web3;
let userAccount;
let transactionId;
const toAddress = `${process.env.NEXT_PUBLIC_RECEIVE_ADDRESS}`;

async function connectWallet() {
    if (typeof window.ethereum !== 'undefined') {
        web3 = new Web3(window.ethereum);
    } else {
        alert('MetaMask not installed!');
    }

    if (typeof window.ethereum !== 'undefined') {
        try {
            // 请求账户访问
            await window.ethereum.request({ method: 'eth_requestAccounts' });
            // 尝试切换到Sepolia测试网
            try {
                await window.ethereum.request({
                    method: 'wallet_switchEthereumChain',
                    params: [{ chainId: '0x1' }] // Sepolia的Chain ID是11155111，十六进制为0xaa36a7
                });
                console.log('Successfully switched to eth network');
            } catch (switchError) {
                // 这个错误代码表明该网络还没有被添加到MetaMask
                if (switchError.code === 4902) {
                    try {
                        await window.ethereum.request({
                            method: 'wallet_addEthereumChain',
                            params: [{
                                chainId: '0x1',
                                chainName: 'ETH Main Network',
                                rpcUrls: ['https://mainnet.infura.io/v3/'], // 替换为有效的Sepolia RPC URL
                                nativeCurrency: {
                                    name: 'ETH',
                                    symbol: 'ETH',
                                    decimals: 18
                                },
                                blockExplorerUrls: ['https://etherscan.io'] // 替换为有效的区块浏览器URL
                            }]
                        });
                        console.log('Successfully added and switched to Sepolia network');
                    } catch (addError) {
                        console.error('Failed to add Sepolia network', addError);
                    }
                } else {
                    console.error('Failed to switch to Sepolia network', switchError);
                }
            }
        } catch (error) {
            console.error('User rejected the request', error);
        }
        try {
            await window.ethereum.request({ method: 'eth_requestAccounts' });
            userAccount = (await web3.eth.getAccounts())[0];
        } catch (error) {
            console.error('connect MetaMask failed:', error);
        }
    } else {
        console.log('MetaMask is not installed. Please install it to use this feature.');
    }
}


async function sendPayment() {
    const amountInEther = 0.0001; // 发送0.001 ETH
    const transactionParameters = {
        from: userAccount,
        to: toAddress, // 替换为接收方地址
        value: '0x' + (amountInEther * 10 ** 18).toString(16), // 0.001 ETH, 转换为十六进制
        // gasPrice: '0x09184e72a000', // 替换为合适的Gas Price
        // gas: '0x2710', // 替换为合适的Gas Limit
    };

    // 发送交易
    try {
        const txHash = await window.ethereum.request({
            method: 'eth_sendTransaction',
            params: [transactionParameters],
        });
        transactionId = txHash;
        return txHash;
    } catch (sendError) {
        console.error('Failed to send transaction', sendError);
    }
}

async function sendERC20Token() {
    // 代币合约的地址和 ABI（需要填入具体的合约地址和 ABI）
    const tokenContractAddress = '0xdac17f958d2ee523a2206206994597c13d831ec7';
    const tokenABI = [
        {
            "constant":false,
            "inputs":[
                {"name":"_to","type":"address"},
                {"name":"_value","type":"uint256"}
            ],
            "name":"transfer",
            "outputs":[],
            "payable":false,
            "stateMutability":"nonpayable",
            "type":"function"},
    ];

    // 创建合约实例
    const web3 = new Web3(window.ethereum);
    const tokenContract = new web3.eth.Contract(tokenABI, tokenContractAddress);
    //const amount = web3.utils.toWei('1000', 'ether'); // 转账金额（根据代币的decimals调整）

    const amount = 20000000;//20u

    // 调用合约的 transfer 方法
    const data = tokenContract.methods.transfer(toAddress, amount).encodeABI();

    // 构造交易对象
    const transactionParameters = {
        to: tokenContractAddress,
        from: userAccount,
        data: data,
        gas: '100000', // 你可能需要根据具体情况调整 gas
    };

    // 发送交易
    try {
        transactionId = await window.ethereum.request({
            method: 'eth_sendTransaction',
            params: [transactionParameters],
        });
        console.log('Transaction hash:', transactionId);
    } catch (error) {
        console.error('Transaction error:', error);
    }
}

async function sendRequest() {
    let config = {
        method: 'get',
        maxBodyLength: Infinity,
        url: `${process.env.NEXT_PUBLIC_API_URL}/api/checkERC20?txHash=` + transactionId,
    };

    axios.request(config)
        .then((response) => {
            console.log(JSON.stringify(response.data));
        })
        .catch((error) => {
            console.log(error);
        });
}



function payByCard() {
    if (typeof window !== "undefined") {
        window.open("https://buy.stripe.com/test_8wMaGl1PD5J019e5kl", "_blank", "noopener,noreferrer");
    }
}



const PaymentDialog = ({ isOpen, onClose }) => {

    if (!isOpen) return null;
    

    async function payByWallet() {
        await connectWallet();
        //await sendPayment();
        await sendERC20Token();
        await sendRequest();
        onClose();
    }


    // const router = useRouter();

    const sty = {
        height: "300px",
        width: "500px",
        bottom: 0, /*底部固定*/
        left: 0, /*实现div的居中*/
        right: 0, /*实现div的居中*/
        top: 0,
        "text-align": "center", /*div的内容居中*/
        "line-height": "80px", /*垂直居中*/
    }


    return (
        <div className='fixed m-auto z-10' style={sty}>
            {/* <ProcessingDialog isDialogOpen={isProcessingDialogOpen} setIsDialogOpen={setIsProcessingDialogOpen}></ProcessingDialog> */}
            {/* <Script
                src="https://js.stripe.com/v3/buy-button.js"
                strategy="beforeInteractive" // 或者 "afterInteractive" 或 "beforeInteractive"
            /> */}

            <Card open={isOpen}>
                <CardHeader>
                    <CardTitle className="text-2xl">
                        <button onClick={onClose} className='absolute right-10'>x</button>
                        <div>Upgrade</div>

                    </CardTitle>
                    <CardDescription>You&apos;re currently on a Free plan. Choose from the plan options below. Upon confirmation, your account will be upgraded and the new pricing will be applied immediately.</CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="grid gap-2">
                        {/* <Label htmlFor="wallet">Web3 Wallet</Label> */}
                        <Button onClick={() => payByWallet("metamask")} variant="outline" className="w-full">
                            Pay by Web3 Wallet
                        </Button>
                    </div>
                    <div className="grid gap-2">
                        <Button onClick={payByCard} variant="outline" className="w-full">
                            Pay by Card
                        </Button>
                    </div>

                    {/* <div className="grid gap-2">
                        <Button variant="outline" className="w-full">
                            Pay by Account Balance
                        </Button>
                    </div> */}
                    {/* https://buy.stripe.com/test_8wMaGl1PD5J019e5kl?locale=en&__embed_source=buy_btn_1PlXwr2LVWfSov9x49yuba3A */}
                    {/* https://buy.stripe.com/test_8wMaGl1PD5J019e5kl?locale=en&__embed_source=buy_btn_1PlXwr2LVWfSov9x49yuba3A */}
                    {/* https://buy.stripe.com/test_8wMaGl1PD5J019e5kl?locale=en&__embed_source=buy_btn_1PlXwr2LVWfSov9x49yuba3A */}
                    {/* <stripe-buy-button
                        buy-button-id="buy_btn_1PlXwr2LVWfSov9x49yuba3A"
                        publishable-key="pk_test_51Pl2IR2LVWfSov9xUiTRYJ2z1vz0ZkFm8AhIIzCBsK4QD0KTt00kUVoepkjmYmwGWXCUjfhcOAD5e2Qy3HIWDKVo00gZk588wa"
                    >
                    </stripe-buy-button> */}
                </CardContent>

                {/* <div className="flex justify-center mt-4 mb-4">
                    <Button
                        variant={isLoginWithEmail ? "outline" : "default"}
                        onClick={() => setIsLoginWithEmail(true)}
                        className="mr-2"
                    >
                        Login with Email
                    </Button>
                    <Button variant={!isLoginWithEmail ? "outline" : "default"} onClick={() => setIsLoginWithEmail(false)}>
                        Login with Web3 Wallet
                    </Button>
                </div> */}
            </Card>
        </div>
    );
};

export default PaymentDialog;